package cn.accp.mvc.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.accp.mvc.entity.Users;
import cn.accp.mvc.service.UsersService;

@Controller
@RequestMapping("/page")
public class UsersController {
	@Autowired
	private UsersService usersService;

	public void setUsersService(UsersService usersService) {
		this.usersService = usersService;
	}
	//ajax請求返回json格式（mvc.xml配置）
	@RequestMapping("/users")
	@ResponseBody
	public String users(String name){
		if (usersService.regsName(name) != null) {
			return "true";
		} else {
			return "false";
		}
	}

	@RequestMapping("/login")
	public void login(Users users, HttpSession session,HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		users = usersService.login(users);
		if (users != null) {
			session.removeAttribute("error");
			session.setAttribute("users", users);
			if (users.isIsadmin()) {
				session.setAttribute("opr", "guanli");
			} else {
				session.setAttribute("opr", "list");
			}
			response.getWriter().println("<script>alert('登录成功！');location.href='/SSM_house/page/gethouseList.do'</script>");
		} else {
			response.getWriter().println("<script>alert('登录失败！');location.href='/SSM_house/page/login.jsp'</script>");
		}
	}

	@RequestMapping("/regs")
	public String regs(Users users, HttpServletRequest request,
			HttpSession session) {
		boolean isOK = false;
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		String telephone = request.getParameter("telephone");
		String username = request.getParameter("username");
		users.setName(name);
		users.setPassword(password);
		if (telephone != "" || telephone != null) {
			users.setTelephone(telephone);
		}
		if (username != "" || username != null) {
			users.setUsername(username);
		}
		isOK = usersService.regs(users);
		if (isOK) {
			session.setAttribute("name", name);
			session.setAttribute("password", password);
			return "/page/login.jsp";
		} else {
			return "/page/regs.jsp";
		}
	}
}
